/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pkwserver;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.security.KeyStore;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.ssl.SslFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

/**
 *
 * @author Pawel
 */
public class PKWClientMina {
    private static final int REMOTE_PORT = 9999;
    
    public static void main(String[] argv) throws Exception {
        IoConnector connector = new NioSocketConnector();
        connector.getSessionConfig().setReadBufferSize(8192);
        
        // SSL stuff
            File pKeyFile = new File("clientkeystore.jks");
            String pKeyPassword = "bskbsk";
            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
            KeyStore keyStore = KeyStore.getInstance("JKS");

            InputStream keyInput = new FileInputStream(pKeyFile);
            keyStore.load(keyInput, pKeyPassword.toCharArray());
            keyInput.close();
            keyManagerFactory.init(keyStore, pKeyPassword.toCharArray());

            SSLContext context = SSLContext.getInstance("TLS");

            context.init(keyManagerFactory.getKeyManagers(), TrustManagerFactory.X509_MANAGERS, null);
        // end SSL stuff
            
        SslFilter sslFilter = new SslFilter(context);
        sslFilter.setUseClientMode(true);
        connector.getFilterChain().addFirst("sslFilter", sslFilter);
        connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));
        
        connector.setHandler(new PKWClientHandler());
        ConnectFuture future = connector.connect(new InetSocketAddress("localhost", REMOTE_PORT));
        future.awaitUninterruptibly();
        if(!future.isConnected()) {
            return;
        }
        IoSession session = future.getSession();
        //session.getConfig().setUseReadOperation(true);
        session.getCloseFuture().awaitUninterruptibly();
        connector.dispose();
    }
}
